import { Context } from 'koa'
import { success, insert, select, update } from '../utils/index'
import { Base64 } from 'js-base64'

export class CodeController {
  static async getCode(ctx: Context) {
    const { pathname } = ctx.request.body as any
    const [rows]: [any, any] = (await select('codes', { pathname })) as [any, any]
    if (!rows.length) {
      throw new Error('代码不存在，请确认代码路径')
    }
    ctx.body = success(ctx, { ...rows[0], code: Base64.encode(rows[0].code) })
  }
  static async updateCode(ctx: Context) {
    const { pathname, hasCode, code: newCode, id } = ctx.request.body as any
    await update('table_config', { id }, { hasCode: 1, modifyTime: Date.now(), modifier: ctx.request.headers.nickname })
    if (hasCode) {
      await update('codes', { pathname }, { code: newCode })
    } else {
      await insert('codes', { pathname, code: newCode })
    }
    ctx.body = success(ctx)
  }
}
